<?php

class SetImageAction extends CAction
{
    private $_recipe;
    private $_succ=false;

    private function renderView()
    {
        $this->controller->layout='simple';
        $this->controller->render('setImage',array('recipe'=>$this->_recipe, 'succ'=>$this->_succ));
    }

    private function validateImage()
    {
        if($this->_recipe->image===null) {
            $this->_recipe->addError('image','图片不能为空');
            return false;            
        }        
        if(!file_exists($this->_recipe->image->getTempName())) {
            $this->_recipe->addError('image','文件大小超过限制');
            return false;            
        }
        if(!UserImage::validateUploadFormat('recipe', $this->_recipe->image->getExtensionName())) {
            $this->_recipe->addError('image','文件格式不正确');
            return false;
        }
        return true;
    }    
        
    public function run()
    {
        if(!isset($_GET['id']))    
            throw new CHttpException(400,'the request is invalid');
    
        $this->_recipe=new Recipe;
        $this->_recipe->id=$_GET['id'];
        if(!isset($_POST['Recipe'])){
            $this->renderView();
            return;        
        }

        $this->_recipe->image=$_POST['Recipe']['image'];
        $this->_recipe->image=CUploadedFile::getInstance($this->_recipe,'image');
        if(!$this->validateImage()) {
            $this->renderView();
            return;        
        }
                
        // lazy loading
        $image = $this->_recipe->image;        
        $this->_recipe=Recipe::loadObjectById($_GET['id'],array('userId','image'));
        if($this->_recipe===null)
            throw new CHttpException(404,'The requested recipe does not exist.');
        if($this->_recipe->userId!=Yii::app()->user->id)
            throw new CHttpException(403,'cannot edit the recipe not belong to you');
        
        $image=UserImage::create('recipe', $image->getTempName());
        if($image===false){
            $this->_recipe->addError('image','保存文件失败');
            $this->renderView();
            return;        
        }
                
        $oldImage=$this->_recipe->image;
        $this->_recipe->image=$image;
        if(!Recipe::saveObject($this->_recipe, array('image','updateTime'))) {
            UserImage::delete('recipe',$this->_recipe->image);
        }
        else {
            UserImage::delete('recipe', $oldImage);                        
            $this->_succ=true;
        }
        
        $this->renderView();
    }
}
  
?>